package org.gpslw.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.api.feature.type.PropertyDescriptor;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.util.Collection;
import java.util.stream.Collectors;

@JsonComponent
public class FeatureTypeSerializer extends JsonSerializer<SimpleFeatureType> {
    @Override
    public void serialize(SimpleFeatureType featureType, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {
        //FeatureType只序列化名称，属性，坐标系等信息
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("name", featureType.getName().getLocalPart());
        Collection<PropertyDescriptor> descriptors = featureType.getDescriptors();
        String descriptorNames = descriptors.stream().map(item -> item.getName().getLocalPart()).collect(Collectors.joining(","));
        jsonGenerator.writeObjectField("descriptors", descriptorNames );
        jsonGenerator.writeObjectField("coordinateReferenceSystem",
                featureType.getCoordinateReferenceSystem().getName().getCodeSpace());
        jsonGenerator.writeEndObject();
    }
}
